﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GameSchool.Models;

namespace GameSchool.DAL
{
    public class HomeRepository : IHomeRepository, IDisposable
    {
        // Nánari upplýsingar um hvernig Repository patternið virkar er á:
        // http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

        /// <summary>
        /// Meðlimabreyta sem er gagnagrunnstengingin
        /// </summary>
        private gsEntities m_db;

        /// <summary>
        /// Class Initializer sem tekur við gagnagrunnstengingu sem skal nota
        /// </summary>
        /// <param name="db"></param>
        public HomeRepository(gsEntities db)
        {
            this.m_db = db;
        }

        /// <summary>
        /// Sækir heiti á deild 
        /// </summary>
        public string GetDepartmentNameById(int departmentDegreeId)
        {
            return m_db.DepartmentDegrees.First(f => f.DepartmentDegreeID == departmentDegreeId).Department.Name;
        }

        public List<Course> GetCoursesStudent(Guid studentUserId)
        {
            return m_db.CourseStudents
                .Where(i => i.StudentUserID == studentUserId)
                .Select(j => j.Course)
                .Where(i => i.IsActive == true)
                .OrderBy(i => i.Name)
                .ToList();
        }

        public List<Course> GetCoursesTeacher(Guid teacherUserId)
        {
            return m_db.Course
                .Where(i => i.TeacherUserID == teacherUserId)
                .OrderBy(i => i.Name)
                .ToList();
        }

        public List<vRecentAdmin> GetRecentAdmin()
        {
            return m_db.vRecentAdmin.OrderByDescending(i => i.RecentDate).ToList();
        }

        public List<vRecentStudent> GetRecentStudent()
        {
            return m_db.vRecentStudent.OrderByDescending(i => i.RecentDate).ToList();
        }

        public List<vRecentTeacher> GetRecentTeacher()
        {
            return m_db.vRecentTeacher.OrderByDescending(i => i.RecentDate).ToList();
        }

        /// <summary>
        /// Vistar breytingar sem gerðar voru í sessioninu
        /// </summary>
        public void Save()
        {
            m_db.SaveChanges();
        }

        #region Disposerinn fyrir using() statement - Alltaf eins
        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    m_db.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}